from PySide6.QtWidgets import (QWidget, QVBoxLayout, QHBoxLayout, QLabel,
                               QPushButton, QTableWidget, QTableWidgetItem,
                               QDialog, QLineEdit, QComboBox, QMessageBox,
                               QFileDialog, QListWidget, QHeaderView)
from PySide6.QtCore import Qt, Signal
from .model import VersionManager, VersionInfo

class VersionEditDialog(QDialog):
    def __init__(self, version=None, parent=None):
        super().__init__(parent)
        self.version = version
        self.init_ui()

    def init_ui(self):
        layout = QVBoxLayout(self)
        self.setWindowTitle("编辑版本信息")

        # 创建表单
        self.name_edit = QLineEdit(self.version.name if self.version else "")
        self.vendor_edit = QLineEdit(self.version.vendor if self.version else "")
        self.file_type_combo = QComboBox()
        self.file_type_combo.addItems(["版本文件", "补丁文件"])
        if self.version:
            self.file_type_combo.setCurrentText(self.version.file_type)

        self.device_models_list = QListWidget()
        if self.version:
            self.device_models_list.addItems(self.version.device_models)

        self.description_edit = QLineEdit(self.version.description if self.version else "")
        self.file_path_edit = QLineEdit(self.version.file_path if self.version else "")
        self.file_select_btn = QPushButton("选择文件")

        # 添加到布局
        form_layout = QVBoxLayout()
        form_layout.addWidget(QLabel("版本名称:"))
        form_layout.addWidget(self.name_edit)
        form_layout.addWidget(QLabel("设备厂商:"))
        form_layout.addWidget(self.vendor_edit)
        form_layout.addWidget(QLabel("文件类型:"))
        form_layout.addWidget(self.file_type_combo)
        form_layout.addWidget(QLabel("支持的设备型号:"))
        form_layout.addWidget(self.device_models_list)

        model_input_layout = QHBoxLayout()
        self.model_input = QLineEdit()
        self.add_model_btn = QPushButton("+")
        self.delete_model_btn = QPushButton("-")
        model_input_layout.addWidget(self.model_input)
        model_input_layout.addWidget(self.add_model_btn)
        model_input_layout.addWidget(self.delete_model_btn)
        form_layout.addLayout(model_input_layout)

        file_layout = QHBoxLayout()
        file_layout.addWidget(self.file_path_edit)
        file_layout.addWidget(self.file_select_btn)
        form_layout.addWidget(QLabel("文件路径:"))
        form_layout.addLayout(file_layout)

        form_layout.addWidget(QLabel("描述:"))
        form_layout.addWidget(self.description_edit)

        # 按钮
        button_layout = QHBoxLayout()
        self.ok_button = QPushButton("确定")
        self.cancel_button = QPushButton("取消")
        button_layout.addWidget(self.ok_button)
        button_layout.addWidget(self.cancel_button)

        layout.addLayout(form_layout)
        layout.addLayout(button_layout)

        # 连接信号
        self.file_select_btn.clicked.connect(self.select_file)
        self.add_model_btn.clicked.connect(self.add_device_model)
        self.delete_model_btn.clicked.connect(self.delete_device_model)
        self.ok_button.clicked.connect(self.accept)
        self.cancel_button.clicked.connect(self.reject)

    def select_file(self):
        file_path, _ = QFileDialog.getOpenFileName(self, "选择文件")
        if file_path:
            self.file_path_edit.setText(file_path)

    def add_device_model(self):
        model = self.model_input.text().strip()
        if model:
            self.device_models_list.addItem(model)
            self.model_input.clear()
            
    def delete_device_model(self):
        selected_items = self.device_models_list.selectedItems()
        if selected_items:
            for item in selected_items:
                row = self.device_models_list.row(item)
                self.device_models_list.takeItem(row)

    def get_version_info(self):
        device_models = [self.device_models_list.item(i).text()
                        for i in range(self.device_models_list.count())]
        return {
            'name': self.name_edit.text(),
            'vendor': self.vendor_edit.text(),
            'file_type': self.file_type_combo.currentText(),
            'device_models': device_models,
            'file_path': self.file_path_edit.text(),
            'description': self.description_edit.text()
        }

class VersionPanel(QWidget):
    def __init__(self, parent=None):
        super().__init__(parent)
        self.version_manager = VersionManager()
        self.init_ui()
        self.load_versions()
    
    def init_ui(self):
        layout = QVBoxLayout(self)
        layout.setContentsMargins(24, 24, 24, 24)
        layout.setSpacing(16)
        
        # 标题
        title = QLabel("版本管理")
        title.setObjectName("panel_title")
        layout.addWidget(title)
        
        # 工具栏
        toolbar = QHBoxLayout()
        self.add_btn = QPushButton("添加版本")
        self.edit_btn = QPushButton("编辑")
        self.delete_btn = QPushButton("删除")
        toolbar.addWidget(self.add_btn)
        toolbar.addWidget(self.edit_btn)
        toolbar.addWidget(self.delete_btn)
        toolbar.addStretch()
        layout.addLayout(toolbar)
        
        # 版本列表
        self.version_table = QTableWidget()
        self.version_table.setColumnCount(8)
        self.version_table.setHorizontalHeaderLabels([
            "序号", "文件类型", "设备厂商", "设备型号", "版本名称",
            "校验码", "文件路径", "描述"
        ])
        self.version_table.setSelectionBehavior(QTableWidget.SelectionBehavior.SelectRows)
        self.version_table.setSelectionMode(QTableWidget.SelectionMode.SingleSelection)
        # 设置表格列宽自适应
        header = self.version_table.horizontalHeader()
        for i in range(self.version_table.columnCount()):
            header.setSectionResizeMode(i, QHeaderView.Stretch)
        layout.addWidget(self.version_table)
        
        # 连接信号
        self.add_btn.clicked.connect(self.add_version)
        self.edit_btn.clicked.connect(self.edit_version)
        self.delete_btn.clicked.connect(self.delete_version)
    
    def load_versions(self):
        versions = self.version_manager.get_all_versions()
        self.version_table.setRowCount(len(versions))
        for row, version in enumerate(versions):
            self.version_table.setItem(row, 0, QTableWidgetItem(str(version.id)))
            self.version_table.setItem(row, 1, QTableWidgetItem(version.file_type))
            self.version_table.setItem(row, 2, QTableWidgetItem(version.vendor))
            self.version_table.setItem(row, 3, QTableWidgetItem(", ".join(version.device_models)))
            self.version_table.setItem(row, 4, QTableWidgetItem(version.name))
            self.version_table.setItem(row, 5, QTableWidgetItem(version.checksum))
            self.version_table.setItem(row, 6, QTableWidgetItem(version.file_path))
            self.version_table.setItem(row, 7, QTableWidgetItem(version.description))
    
    def add_version(self):
        dialog = VersionEditDialog(parent=self)
        if dialog.exec_():
            info = dialog.get_version_info()
            checksum = self.version_manager.calculate_checksum(info['file_path'])
            version = VersionInfo(
                id=0,
                checksum=checksum,
                **info
            )
            self.version_manager.add_version(version)
            self.load_versions()
    
    def edit_version(self):
        current_row = self.version_table.currentRow()
        if current_row < 0:
            QMessageBox.warning(self, "警告", "请先选择要编辑的版本")
            return
        
        version_id = int(self.version_table.item(current_row, 0).text())
        version = self.version_manager.get_version(version_id)
        if not version:
            return
        
        dialog = VersionEditDialog(version, parent=self)
        if dialog.exec_():
            info = dialog.get_version_info()
            checksum = self.version_manager.calculate_checksum(info['file_path'])
            updated_version = VersionInfo(
                id=version.id,
                checksum=checksum,
                **info
            )
            self.version_manager.update_version(updated_version)
            self.load_versions()
    
    def delete_version(self):
        current_row = self.version_table.currentRow()
        if current_row < 0:
            QMessageBox.warning(self, "警告", "请先选择要删除的版本")
            return
        
        version_id = int(self.version_table.item(current_row, 0).text())
        reply = QMessageBox.question(
            self, "确认", "确定要删除这个版本吗？",
            QMessageBox.StandardButton.Yes | QMessageBox.StandardButton.No
        )
        
        if reply == QMessageBox.StandardButton.Yes:
            self.version_manager.remove_version(version_id)
            self.load_versions()